/**
 * 预加载脚本 - 抖音发布器模块
 * 
 * 为渲染进程提供安全的 API 接口
 */

const { contextBridge, ipcRenderer } = require('electron');

// 暴露安全的 API 到渲染进程
contextBridge.exposeInMainWorld('electronAPI', {
  // 账号管理相关
  openDouyinLogin: () => ipcRenderer.invoke('douyin-open-login'),
  getCookies: () => ipcRenderer.invoke('douyin-get-cookies'),
  saveAccount: (accountData) => ipcRenderer.invoke('douyin-save-account', accountData),
  getAccounts: () => ipcRenderer.invoke('douyin-get-accounts'),
  getAccountById: (accountId) => ipcRenderer.invoke('douyin-get-account-by-id', accountId),
  deleteAccount: (accountId) => ipcRenderer.invoke('douyin-delete-account', accountId),
  updateAccount: (accountData) => ipcRenderer.invoke('douyin-update-account', accountData),
  updateAccountCookies: (updateData) => ipcRenderer.invoke('douyin-update-account-cookies', updateData),

  // 发布相关
  openDouyinPublish: (contentData) => ipcRenderer.invoke('douyin-open-publish', contentData),
  savePublishRecord: (recordData) => ipcRenderer.invoke('douyin-save-publish-record', recordData),
  updatePublishRecordStatus: (recordId, statusData) => 
    ipcRenderer.invoke('douyin-update-publish-record-status', recordId, statusData),
  getPublishRecords: () => ipcRenderer.invoke('douyin-get-publish-records'),

  // 工具方法
  showMessage: (title, content) => {
    console.log(`${title}: ${content}`);
  },

  // 网络请求API (解决跨域问题)
  fetch: async (url, options) => {
    const response = await ipcRenderer.invoke('network:fetch', url, options);
    
    // 创建一个类似fetch Response的对象，添加便捷方法
    return {
      ok: response.ok,
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
      
      // 返回文本数据
      text: () => Promise.resolve(response.text),
      
      // 解析JSON数据
      json: () => {
        try {
          return Promise.resolve(JSON.parse(response.text));
        } catch (e) {
          return Promise.reject(new Error('Invalid JSON'));
        }
      },
      
      // 返回ArrayBuffer（用于二进制数据如图片、视频等）
      arrayBuffer: () => {
        try {
          const binaryString = atob(response.data);
          const bytes = new Uint8Array(binaryString.length);
          for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }
          return Promise.resolve(bytes.buffer);
        } catch (e) {
          return Promise.reject(new Error('Failed to decode binary data'));
        }
      },
      
      // 返回Blob（用于文件下载等）
      blob: () => {
        try {
          const binaryString = atob(response.data);
          const bytes = new Uint8Array(binaryString.length);
          for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }
          const contentType = response.headers['content-type'] || 'application/octet-stream';
          return Promise.resolve(new Blob([bytes], { type: contentType }));
        } catch (e) {
          return Promise.reject(new Error('Failed to create blob'));
        }
      }
    };
  },

  // 发布状态更新回调
  onPublishStatusUpdate: (callback) => {
    ipcRenderer.on('publish-status-update', (event, data) => {
      callback(data);
    });
  }
});

// 为向后兼容，也暴露原有的 ipcRenderer 方法
contextBridge.exposeInMainWorld('douyinPublisher', {
  invoke: (channel, ...args) => {
    // 只允许调用抖音发布器相关的 IPC 方法
    const allowedChannels = [
      'douyin-open-login',
      'douyin-get-cookies',
      'douyin-save-account',
      'douyin-get-accounts',
      'douyin-get-account-by-id',
      'douyin-delete-account',
      'douyin-update-account',
      'douyin-update-account-cookies',
      'douyin-open-publish',
      'douyin-save-publish-record',
      'douyin-update-publish-record-status',
      'douyin-get-publish-records'
    ];
    
    if (allowedChannels.includes(channel)) {
      return ipcRenderer.invoke(channel, ...args);
    } else {
      throw new Error(`不允许的 IPC 频道: ${channel}`);
    }
  }
});
